package com.xing.yunji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xing.yunji.common.BaseResponse;
import com.xing.yunji.common.DeleteRequest;
import com.xing.yunji.common.ErrorCode;
import com.xing.yunji.common.ResultUtils;
import com.xing.yunji.exception.BusinessException;
import com.xing.yunji.model.domain.Team;
import com.xing.yunji.model.domain.User;
import com.xing.yunji.model.domain.UserTeam;
import com.xing.yunji.model.dto.TeamQuery;
import com.xing.yunji.model.request.team.TeamAddRequest;
import com.xing.yunji.model.request.team.TeamJoinRequest;
import com.xing.yunji.model.request.team.TeamQuitRequest;
import com.xing.yunji.model.request.team.TeamUpdateRequest;
import com.xing.yunji.model.vo.TeamUserVO;
import com.xing.yunji.service.TeamService;
import com.xing.yunji.service.UserService;
import com.xing.yunji.service.UserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 队伍接口
 *
 * @author xing
 */
@RestController
@RequestMapping("/team")
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:8081","http://soothing.icu:81"})
@Slf4j
public class TeamController {

    @Resource
    private UserService userService;

    @Resource
    private TeamService teamService;

    @Resource
    private UserTeamService userTeamService;

    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        if (teamAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        long teamId = teamService.addTeam(team, loginUser);
        return ResultUtils.success(teamId);

    }

//    @PostMapping("/delete")
//    public BaseResponse<Boolean> deleteTeam(@RequestBody long id) {
//        if (id <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        boolean result = teamService.removeById(id);
//        if (!result) {
//            throw new BusinessException(ErrorCode.SYSTEM_EXCEPTION, "解散队伍失败");
//        }
//        return ResultUtils.success(true);
//    }


    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
        if (teamUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.updateTeam(teamUpdateRequest, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_EXCEPTION, "更新队伍失败");
        }
        return ResultUtils.success(true);
    }

    @GetMapping("/get")
    public BaseResponse<Team> getTeamById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "该队伍不存在");
        }
        return ResultUtils.success(team);
    }


    //    @GetMapping("/list")
//    public BaseResponse<List<Team>> listTeams(TeamQuery teamQuery){
//        if (teamQuery == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        Team team = new Team();
//        BeanUtils.copyProperties(teamQuery,team);
//        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
//        List<Team> teamList = teamService.list(queryWrapper);
//        return ResultUtils.success(teamList);
//    }

    /**
     * 分页查询队伍列表，并关联查询已加入队伍的用户信息
     *
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> listTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean isAdmin = userService.isAdmin(request);
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, isAdmin);
        markTeamWithHasJoin(request, teamList);


        //根据队伍id进行分组，统计已加入队伍的人数
        List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).collect(Collectors.toList());
        List<UserTeam> userTeamList = userTeamService.list(new LambdaQueryWrapper<UserTeam>().in(UserTeam::getTeamId, teamIdList));
        Map<Long, List<UserTeam>> collect = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teamList.forEach(team->{
            team.setHasJoinNum(collect.getOrDefault(team.getId(),new ArrayList<>()).size());
        });
        return ResultUtils.success(teamList);

    }

    /**
     *  将teamList中的已加入的队伍打上hasJoin标记，方便进行队伍的权限控制
     * @param request
     * @param teamList
     */
    private void markTeamWithHasJoin(HttpServletRequest request, List<TeamUserVO> teamList) {
        List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).collect(Collectors.toList());
        Long loginUserId = userService.getLoginUser(request).getId();
        List<UserTeam> userTeamList = userTeamService.list(new LambdaQueryWrapper<UserTeam>()
                .eq(UserTeam::getUserId, loginUserId)
                .in(UserTeam::getTeamId, teamIdList));
        Set<Long> hasJoinTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
        teamList.forEach(team -> {
            boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
            team.setHasJoin(hasJoin);
        });
    }


    @GetMapping("/list/page")
    public BaseResponse<Page<Team>> listTeamsByPage(TeamQuery teamQuery) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamQuery, team);
        Page<Team> page = new Page<>(teamQuery.getPageNum(), teamQuery.getPageSize());
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> resultPage = teamService.page(page, queryWrapper);
        return ResultUtils.success(resultPage);
    }

    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = teamService.joinTeam(teamJoinRequest, request);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_EXCEPTION, "加入队伍失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 获取我加入的队伍
     *
     * @param request
     * @return
     */
    @GetMapping("/list/my/join")
    public BaseResponse<List<TeamUserVO>> listMyJoinTeams(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId());
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
        // 取出不重复的队伍 id
        // teamId userId
        // 1, 2
        // 1, 3
        // 2, 3
        // result
        // 1 => 2, 3
        // 2 => 3
        Map<Long, List<UserTeam>> listMap = userTeamList.stream()
                .collect(Collectors.groupingBy(UserTeam::getTeamId));
        List<Long> idList = new ArrayList<>(listMap.keySet());
        TeamQuery teamQuery = new TeamQuery();
        //要查询的队伍id列表
        teamQuery.setIdList(idList);

        return this.listTeams(teamQuery,request);


    }

    @GetMapping("/list/my/create")
    public BaseResponse<List<TeamUserVO>> listMyCreateTeams(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        TeamQuery teamQuery = new TeamQuery();
        teamQuery.setUserId(loginUser.getId());
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, true);
        markTeamWithHasJoin(request,teamList);
        return ResultUtils.success(teamList);

    }

    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        if (teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = teamService.quitTeam(teamQuitRequest, request);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_EXCEPTION, "退出队伍失败");
        }
        return ResultUtils.success(true);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        long id = deleteRequest.getId();
        if (deleteRequest == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = teamService.deleteTeam(id, request);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_EXCEPTION, "解散队伍失败");
        }
        return ResultUtils.success(true);
    }

}
